package com.mazegame.frontend;

import com.mazegame.backend.StorySceneManager;
import com.mazegame.backend.TextAnimation;
import com.mazegame.backend.UserDAO;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.media.AudioClip;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.net.URISyntaxException;

import javafx.scene.control.Label;


public class SecondStoryPanel extends JPanel implements GamePanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private JLayeredPane layeredPane;
    private static final int WIDTH = 1500;
    private static final int HEIGHT = 900;
    private JFXPanel jfxPanel;
    private static StorySceneManager sceneManager;// 故事场景管理器
    int userId;// 获取当前登录的用户名和ID
    int targetChapter = 2;// 当前章节
    private static AudioClip typingSound; // 音效对象

    static double volume = 0.5;

    //第一个场景要用到的
    private TextAnimation animation1;
    private Text text1;
    private static final String CONTENT1 = "\u3000\u3000你利用收集的星辰之力照亮周围照亮前路，时间缓缓流过，星辰变换，迷宫内部也变换着，在转角处迷宫墙壁由沙变为石头，前方有一道石门，你推动石门里面是第二个迷宫。";
    private boolean isFirstClick1 = true;// 标记是否是第一次点击

    // 第二个场景要用到的
    private TextAnimation animation2;
    private Text text2;
    private static final String CONTENT2 = "\u3000\u3000看来接下来看来要通过第二层试炼了。";
    private boolean isFirstClick2 = true;


    // 第三个场景要用到的
    private static TextAnimation animation3;
    private static Text text3;
    private static final String CONTENT3 = "\u3000\u3000经过试炼以后，你阅读迷宫中留下的历史正文，文字中记载着人们幸福的生活因为一群外来人而彻底打乱，整个城市变得不再充满笑语。你的心情变得沉重起来。";
    private boolean isFirstClick3 = true;

    // 第四个场景要用到的
    private TextAnimation animation4;
    private Text text4;
    private static final String CONTENT4 = "\u3000\u3000你暗自说到：“入侵者吗...只有收集到完整的历史正文，才能知道这个曾经以探索天文而闻名的城市是如何消失的又为何只留下天枢之眼。";
    private boolean isFirstClick4 = true;



    public SecondStoryPanel(CardLayout cardLayout, JPanel cardPanel) {
        this.cardLayout = cardLayout;
        this.cardPanel = cardPanel;
        initializeUI();
    }

    private void initializeUI() {
        // 使用 JLayeredPane 管理不同层级的组件
        layeredPane = new JLayeredPane();
        setLayout(new BorderLayout());
        add(layeredPane, BorderLayout.CENTER);
        // 创建 JavaFX 内容面板
        jfxPanel = new JFXPanel();
        jfxPanel.setOpaque(false);
        jfxPanel.setBounds(0, 0, WIDTH, HEIGHT);
        layeredPane.add(jfxPanel, JLayeredPane.MODAL_LAYER);
        Platform.runLater(() -> {
            // 创建场景管理器
            sceneManager = new StorySceneManager();
            // 创建主容器
            BorderPane root = createContentPane();
            root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
            // 将场景管理器的根节点添加到主容器中心
            root.setCenter(sceneManager.getRoot());
            // 创建透明场景
            Scene scene = new Scene(root, WIDTH, HEIGHT, javafx.scene.paint.Color.TRANSPARENT);
            jfxPanel.setScene(scene);
            // 初始化并显示第一个场景
            initScenes();
            sceneManager.showScene("scene0");
        });
    }

    private BorderPane createContentPane() {
        return new BorderPane();
    }

    // 初始化故事中的所有场景

    private void initScenes() {
        StackPane scene0 = createScene0();
        sceneManager.addScene("scene0", addBackground(scene0, "/img/黑色背景.png"));
        StackPane scene1 = createScene1();
        sceneManager.addScene("scene1", addBackground(scene1, "/img/手.jpg"));
        StackPane scene2 = createScene2();
        sceneManager.addScene("scene2", addBackground(scene2, "/img/主角对话.png"));
        StackPane scene3 = createScene3();
        sceneManager.addScene("scene3", addBackground(scene3, "/img/石头2.png"));
        StackPane scene4 = createScene4();
        sceneManager.addScene("scene4", addBackground(scene4, "/img/主角对话.png"));
        StackPane scene5 = createScene5();
        sceneManager.addScene("scene5", addBackground(scene5, "/img/黑色背景.png"));
    }
    // 添加背景图的方法
    private Pane addBackground(Pane content, String imagePath) {
        ImageView background = new ImageView(new Image(getClass().getResourceAsStream(imagePath)));
        background.setFitWidth(WIDTH);
        background.setFitHeight(HEIGHT);
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(background, content);
        return stackPane;
    }

    private StackPane createScene0() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第二章");
        content.setWrappingWidth(900);
        content.setFont(new javafx.scene.text.Font("微软雅黑", 48));
        content.setFill(javafx.scene.paint.Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        root.setMargin(textbox,new javafx.geometry.Insets(0,0,200, 520));
        root.setMargin(tip,new javafx.geometry.Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        // 添加点击事件：点击任意位置切换到下一个场景
        root.setOnMouseClicked(event -> {
            startFirstStory1();
        });
        return root;
    }
    private StackPane createScene1() {
        // 构建文本1
        text1 = new Text("");
        text1.setWrappingWidth(860);
        text1.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text1.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().add(text1);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(900, 300);
        textbox.setMaxSize(900, 300);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0 ,100,0));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick1) {
                stopAnimationAndSound1();
                isFirstClick1 = false;  // 更新状态为已点击一次
            } else {
                // 第二次点击：跳转到下一个场景
                startFirstStory2();
            }
        });
        return stackPane;
    }
    private StackPane createScene2() {
        // 构建文本1
        text2 = new Text("");
        text2.setWrappingWidth(600);
        text2.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text2.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text2);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(640, 200);
        textbox.setMaxSize(640, 200);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        StackPane.setMargin(textbox, new javafx.geometry.Insets(240,0 ,0,80));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick2) {
                stopAnimationAndSound2();
                isFirstClick2 = false;  // 更新状态为已点击一次
            } else {
                //进迷宫
                MazeGeneratePanel.isFirst = true;
                BufferPanel.isFirst = true;
                cardLayout.show(cardPanel,"MAZEGENERATEPANEL");
            }
        });
        return stackPane;
    }
    private StackPane createScene3() {
        // 构建文本1
        text3 = new Text("");
        text3.setWrappingWidth(860);
        text3.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text3.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text3);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(900, 240);
        textbox.setMaxSize(900, 240);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);
        StackPane.setMargin(textbox, new javafx.geometry.Insets(0,0 ,0,0));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick3) {
                stopAnimationAndSound3();
                isFirstClick3 = false;  // 更新状态为已点击一次
            } else {
                startFirstStory4();
            }
        });
        return stackPane;
    }
    private StackPane createScene4() {
        // 构建文本1
        text4 = new Text("");
        text4.setWrappingWidth(800);
        text4.setFont(new javafx.scene.text.Font("微软雅黑", 32));
        text4.setFill(javafx.scene.paint.Color.BLACK);
        // 文本容器
        VBox textbox = new VBox(20);//每个文本间隔20
        textbox.getChildren().addAll(text4);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(20));//页边距20
        textbox.setPrefSize(840, 200);
        textbox.setMaxSize(840, 200);
        textbox.setStyle("-fx-background-color: rgba(255, 255, 255, 0.6);" +
                "-fx-border-radius: 40;" +
                "-fx-background-radius: 40;" +
                "-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 10, 0, 0, 0);" +
                "-fx-stroke: grey;"
        );
        javafx.scene.control.Label tip = new javafx.scene.control.Label("点击任意位置继续...");
        tip.setFont(javafx.scene.text.Font.font("KaiTi", FontWeight.BOLD, 48));
        tip.setTextFill(javafx.scene.paint.Color.WHITE);

        StackPane.setMargin(textbox, new javafx.geometry.Insets(240,0,0,160));
        StackPane.setMargin(tip, new javafx.geometry.Insets(640,0 ,0,0));
        // 布局容器
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(textbox,tip);//添加到面板
        // 添加点击事件：点击任意位置切换到下一个场景
        stackPane.setOnMouseClicked(event -> {
            if (isFirstClick4) {
                stopAnimationAndSound4();
                isFirstClick4 = false;  // 更新状态为已点击一次
            } else {
                sceneManager.showScene("scene5");
            }
        });
        return stackPane;
    }
    private StackPane createScene5() {
        StackPane root = new StackPane();
        Text content = new Text("\u3000\u3000第二章结束");
        content.setWrappingWidth(900);
        content.setFont(new javafx.scene.text.Font("微软雅黑", 48));
        content.setFill(javafx.scene.paint.Color.WHITE);
        content.setVisible(true);
        VBox textbox = new VBox(40);//每个文本间隔20
        textbox.getChildren().add(content);//把文本放进面板
        textbox.setAlignment(Pos.CENTER);//文本居中放置
        textbox.setPadding(new javafx.geometry.Insets(0));//页边距20
        textbox.setPrefSize(900, 600);
        textbox.setMaxSize(900, 600);
        javafx.scene.control.Label tip = new Label("点击任意位置继续...");
        tip.setFont(Font.font("KaiTi", FontWeight.BOLD, 32));
        tip.setTextFill(Color.WHITE);
        root.setMargin(textbox,new javafx.geometry.Insets(0,0,200, 430));
        root.setMargin(tip,new Insets(500,0,0,0));
        root.getChildren().addAll(textbox, tip);
        root.setOnMouseClicked(event -> {
            update();
        });

        return root;
    }

    private void update() {
        targetChapter = 3; // 解锁第三章节
        if(targetChapter>ChapterPanel.currentChapter){
            userId = Integer.parseInt(LoginPanel.currentUserId);
            // 保存游戏进度
            if (UserDAO.updateChapter(userId, targetChapter)) {
                System.out.println("游戏进度保存成功！");
            } else {
                System.out.println("游戏进度保存失败！");
            }
            ChapterPanel.update();
        }
        // 切换回章节界面
        cardLayout.show(cardPanel, "CHAPTERPANEL");
        // 重置
        text1.setText("");
        text2.setText("");
        text3.setText("");
        text4.setText("");
        isFirstClick1 = true;
        isFirstClick2 = true;
        isFirstClick3 = true;
        isFirstClick4 = true;
        sceneManager.showScene("scene0");
    }
    public void stopAnimationAndSound1(){
        // 停止动画和音效，显示全文
        if (animation1 != null) {
            animation1.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text1.setText(CONTENT1);
        isFirstClick1 = false;
    }
    public void stopAnimationAndSound2(){
        // 停止动画和音效，显示全文
        if (animation2 != null) {
            animation2.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text2.setText(CONTENT2);
        isFirstClick2 = false;
    }
    public void stopAnimationAndSound3(){
        // 停止动画和音效，显示全文
        if (animation3 != null) {
            animation3.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text3.setText(CONTENT3);
        isFirstClick3 = false;
    }
    public void stopAnimationAndSound4(){
        // 停止动画和音效，显示全文
        if (animation4 != null) {
            animation4.stop(); // 现在可以调用 stop
        }
        typingSound.stop();
        text4.setText(CONTENT4);
        isFirstClick4 = false;
    }
    public void startFirstStory1() {
        sceneManager.showScene("scene1");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动文本动画
        animation1 = new TextAnimation(
                text1,
                CONTENT1,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation1.start();
    }
    public void startFirstStory2() {
        sceneManager.showScene("scene2");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = getClass().getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动文本动画
        animation2 = new TextAnimation(
                text2,
                CONTENT2,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation2.start();
    }
    public static void startFirstStory3() {
        sceneManager.showScene("scene3");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = SecondStoryPanel.class.getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动第一个文本动画
        animation3 = new TextAnimation(
                text3,
                CONTENT3,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation3.start();
    }
    public void startFirstStory4() {
        sceneManager.showScene("scene4");
        // 加载音效
        URI soundUri = null;
        try {
            soundUri = FirstStoryPanel.class.getResource("/music/打字机音效.wav").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        typingSound = new AudioClip(soundUri.toString());
        typingSound.setVolume(volume);//音量
        typingSound.setCycleCount(AudioClip.INDEFINITE);//无限循环播放
        // 启动本动画
        animation4 = new TextAnimation(
                text4,
                CONTENT4,
                TextAnimation.DEFAULT_CHARACTER_DELAY,
                TextAnimation.DEFAULT_TEXT_DELAY,
                typingSound
        );
        animation4.start();
    }


    @Override
    public void showPanel() {
        cardLayout.show(cardPanel, "SECONDSTORYPANEL");
    }

    @Override
    public void cleanup() {
        // 清理资源
    }


}